package pers.qianyu.module.system.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import pers.qianyu.module.core.constants.TokenConstants;
import pers.qianyu.module.core.domain.system.vo.SysUserVO;
import pers.qianyu.module.system.exception.SysErrorCodeEnum;
import pers.qianyu.module.system.exception.SysException;
import pers.qianyu.module.system.listener.events.UserFollowedUserIdsUpdatedEvent;

import java.util.Objects;
import java.util.Set;

/**
 * @author mizzle rain
 * @date 2021-04-07 18:57
 */
@Component
public class UserFollowedUserIdsUpdatedEventListener implements ApplicationListener<UserFollowedUserIdsUpdatedEvent> {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onApplicationEvent(UserFollowedUserIdsUpdatedEvent event) {
        Long userId = event.getUserId();
        Set<Long> followedUserIds = event.getFollowedUserIds();

        Object token = redisTemplate.opsForValue().get(TokenConstants.USER_ID_PREFIX + userId);
        if (Objects.nonNull(token)) {
            Object value = redisTemplate.opsForValue().get(token);
            if (Objects.nonNull(value)) {
                SysUserVO sysUserVO;
                try {
                    sysUserVO = (SysUserVO) value;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SysException(SysErrorCodeEnum.INVALID_TOKEN);
                }
                sysUserVO.setFollowedUserIds(followedUserIds);
                redisTemplate.opsForValue().set((String) token, sysUserVO, TokenConstants.TOKEN_EXPIRE_TIME);
            }
        }
    }
}
